package com.angus.modules.content.service.impl;

import com.angus.api.content.domain.OrderCommission;
import com.angus.modules.content.domain.SysOrder;
import com.angus.modules.content.dto.QueryBaseDto;
import com.angus.modules.content.dto.SysFinanceDto;
import com.angus.modules.content.repository.OrderCommissionRepository;
import com.angus.modules.content.repository.SysOrderRepository;
import com.angus.modules.content.service.SysFinanceService;
import com.angus.modules.content.vo.FinanceVo;
import com.angus.modules.content.vo.SysOrderVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import com.angus.common.core.text.Convert;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * 财务服务实现类
 * @author lineCode
 * @date 2025-08-17
 */
@Slf4j
@Service
public class SysFinanceServiceImpl implements SysFinanceService {
    /**
     * 订单表
     */
    @Resource
    private SysOrderRepository sysOrderRepository;
    /**
     * 订单佣金表
     */
    @Resource
    private OrderCommissionRepository orderCommissionRepository;
    /**
     * 缴费记录
     * @param dto 原始查询参数
     * @return 订单列表
     */
    @Override
    public FinanceVo<SysOrderVo> getPayFeesList(QueryBaseDto dto) {
        SysFinanceDto sysFinanceDto = SysFinanceDto.mapToDto(dto.getSearchExtend());
        List<SysOrder> orderData = sysOrderRepository.getPayFeesList(dto, sysFinanceDto);
        // 转换 VO
        FinanceVo<SysOrderVo> vo = new FinanceVo<>();
        if (!orderData.isEmpty()) {
            log.info("查询缴费记录，参数：{}", sysFinanceDto);
            // 总数量
            int totalCount = sysOrderRepository.countOrder(
                    sysFinanceDto.getOrderNo(),
                    sysFinanceDto.getCourseCode(),
                    sysFinanceDto.getStatus(),
                    sysFinanceDto.getPayMethod(),
                    sysFinanceDto.getStartTime(),
                    sysFinanceDto.getEndTime(),
                    false
            );
            log.info("总计录数：{}", totalCount);
            // 总数量
            vo.setTotalCount(totalCount);
            // 分页数据
            vo.setData(SysOrderVo.mapToVo(orderData));
            // 金额统计
            vo.setTotalAmount(orderData.stream().map(SysOrder::getCourseAmount).reduce(BigDecimal.ZERO, BigDecimal::add));
        }
        return vo;
    }

    /**
     * 订单佣金列表查询
     * @param dto 订单佣金查询参数
     * @return 分页后的订单佣金VO列表，包含佣金相关信息
     */
    @Override
    public FinanceVo<OrderCommission> getOrderCommissionList(QueryBaseDto dto) {
        SysFinanceDto sysFinanceDto = SysFinanceDto.mapToDto(dto.getSearchExtend());
        // 参数校验
        int page = Math.max(dto.getPageNum(), 1);
        // 限制最大条数
        int limit = Math.max(1, Math.min(dto.getPageSize(), 100));
        // 计算偏移量
        int offset = (page - 1) * limit;
        // 转换 VO
        FinanceVo<OrderCommission> vo = new FinanceVo<>();
        // 查询订单佣金列表
        List<OrderCommission> orderCommissionList = orderCommissionRepository.getOrderCommissionList(
                sysFinanceDto.getOrderNo(), sysFinanceDto.getCourseCode(), sysFinanceDto.getCourseName(), sysFinanceDto.getUserId(), offset, limit);
        if (orderCommissionList.isEmpty()) {
            vo.setTotalCount(0);
            vo.setTotalAmount(BigDecimal.ZERO);
            vo.setTotalCommissionAmount(BigDecimal.ZERO);
            return vo;
        }
        // 查询统计
        int totalCount = orderCommissionRepository.countOrderCommission(sysFinanceDto.getOrderNo(), sysFinanceDto.getCourseCode(), sysFinanceDto.getCourseName());
        // 金额统计
        Map<String, Object> summaryResp = orderCommissionRepository.getOrderCommissionSummary(sysFinanceDto.getOrderNo(), sysFinanceDto.getCourseCode());
        // 1. 防止 summaryResp 本身为 null
        summaryResp = Objects.isNull(summaryResp) ? new HashMap<>() : summaryResp;
        // 2. 安全获取并转换 courseAmount（默认 0）
        BigDecimal totalCourseAmount = Convert.toBigDecimal(summaryResp.get("courseAmount"), BigDecimal.valueOf(0.00));
        // 3. 安全获取并转换 commissionAmount（默认 0）
        BigDecimal totalCommissionAmount = Convert.toBigDecimal(summaryResp.get("commissionAmount"), BigDecimal.valueOf(0.00));
        // 分页数据
        vo.setData(orderCommissionList);
        // 总数量
        vo.setTotalCount(totalCount);
        // 金额统计
        vo.setTotalAmount(totalCourseAmount);
        vo.setTotalCommissionAmount(totalCommissionAmount);
        return vo;
    }

    /**
     * 订单收益
     * @param dto 查询参数
     * @return 订单收益
     */
    @Override
    public FinanceVo<Map<String, Object>> getPayFeesProfit(QueryBaseDto dto) {
        SysFinanceDto sysFinanceDto = SysFinanceDto.mapToDto(dto.getSearchExtend());
        List<Map<String, Object>> orderProfit = sysOrderRepository.getPayFeesProfit(sysFinanceDto.getStartTime(), sysFinanceDto.getEndTime(), sysFinanceDto.getCourseName());
        // 转换 VO
        FinanceVo<Map<String, Object>> vo = new FinanceVo<>();
        vo.setData(orderProfit);
        return vo;
    }
}


